<template>
  <div>

    <!--<el-row style="background-color: #F2F6FC">-->
      <!--<el-col :span="24" style="margin: 5px">-->
        <!--<span>-->
          <!--状态: <el-tag :type="stateType[stateIndex]" style="margin-right: 5px">{{state[stateIndex]}}</el-tag>-->
          <!--<el-button type="primary" icon="el-icon-phone" size="mini" @click="signInFormVisible = true" :disabled="stateIndex != 0">连接服务器</el-button>-->
        <!--</span>-->

        <!--<span v-if="stateIndex != 0" style="margin-left: 10px">-->
          <!--<el-button v-if="stateIndex === 1" type="primary" icon="el-icon-success" size="mini" @click="clickLogin">签入</el-button>-->
          <!--<el-button v-if="stateIndex === 2" type="info" icon="el-icon-error" size="mini" @click="clickLogin">签出</el-button>-->
        <!--</span>-->

        <!--<span style="margin-left: 10px">-->
          <!--<span>-->
            <!--<el-tag :type="phoneType[phoneIndex]" size="mini">{{phoneState[phoneIndex]}}</el-tag>-->
          <!--</span>-->


          <!--<el-input placeholder="请输入手机号" v-model="inputPhone" clearable size="mini" style="width: 150px;"></el-input>-->
          <!--<el-button size="mini" @click="clickWaiHu">外拨</el-button>-->
        <!--</span>-->

        <!--<span style="margin-left: 10px">-->
          <!--<span v-if="canHuangUpVisible">-->
            <!--<el-button type="danger" size="mini"  @click="clickHuangUp" style="margin-left: 0">挂断</el-button>-->
            <!--<el-button id="btnJingYin" type="warning" size="mini" @click="clickJingYin" style="margin-left: 0">静音</el-button>-->
            <!--<el-button type="success" size="mini" style="margin-left: 0">转接</el-button>-->
          <!--</span>-->
          <!--<span v-else>-->
            <!--<el-button type="danger" size="mini" style="margin-left: 0" @click="clickHuangUp" disabled>挂断</el-button>-->
            <!--<el-button id="btnJingYin" type="warning" size="mini" style="margin-left: 0" @click="clickJingYin" disabled>静音</el-button>-->
            <!--<el-button type="success" size="mini" style="margin-left: 0" @click="clickZhuanJie" disabled>转接</el-button>-->
          <!--</span>-->

          <!--<el-button id="btnAnswer" type="info" size="mini" style="margin-left: 0">摘机</el-button>-->
        <!--</span>-->

        <!--<span v-if="stateIndex == 2">-->
          <!--<span v-if="timer" style="margin-left: 20px">-->
            <!--正在通话 {{callMinute}} : {{callSecond}}-->
          <!--</span>-->
        <!--</span>-->
      <!--</el-col>-->
    <!--</el-row>-->

    <el-row>
      <el-col :span="18">
        <el-input placeholder="请输入手机号" v-model="inputPhone" clearable size="mini" style="width: 150px;"></el-input>
        <!--<el-button size="mini" icon="el-icon-phone-outline" @click="clickWaiHu" circle></el-button>-->

        <el-button v-if="phoneIndex === 0" size="mini" @click="clickWaiHu" circle><i class="iconfont icon-weibiaoti-"></i></el-button>
        <!--<el-button v-else-if="phoneIndex === 1" size="mini" @click="clickWaiHu" circle><i class="iconfont icon-weibiaoti-"></i></el-button>-->
        <el-button v-else size="mini" @click="clickWaiHu" circle style="background-color: #F56C6C"><i class="iconfont icon-guaduan"></i></el-button>

        <el-button v-if="phoneIndex !== 2" size="mini" circle disabled><i class="iconfont icon-maikefeng-jingyin"></i></el-button>
        <el-button v-else-if="phoneIsJingYin === false" size="mini" circle @click="clickJingYin"><i class="iconfont icon-maikefeng-jingyin"></i></el-button>
        <el-button v-else size="mini" circle @click="clickJingYin" style="background-color: #F56C6C"><i class="iconfont icon-maikefeng-jingyin"></i></el-button>

        <el-button size="mini" @click="clickZhuanJie" circle><i class="iconfont icon-youjiantou"></i></el-button>

        <span v-if="phoneIndex === 1" style="margin-left: 5px; color: #67C23A">
          正在外呼中 ...
        </span>
        <span v-if="phoneIndex === 2">
          <span v-if="timer" style="margin-left: 20px; color: #67C23A">
            通话时长 {{callMinute}} : {{callSecond}}
          </span>
        </span>
      </el-col>

      <el-col :span="6" style="text-align: right;">
        <el-button size="mini" :type="stateType[stateIndex]">{{state[stateIndex]}}</el-button>
        <el-button size="mini" :type="loginType[stateIndex]" @click="clickDengLu">{{loginState[stateIndex]}}</el-button>
      </el-col>
    </el-row>

    <!--<span style="margin-right: 10px; color: #409EFF">-->
      <!--当前状态: <el-tag :type="stateType[stateIndex]">{{state[stateIndex]}}</el-tag>-->
    <!--</span>-->

    <el-dialog title="请输入账号信息" :visible.sync="signInFormVisible" width="20%">
      <el-form ref="signInfo" :model="signInfo" :inline="true" style="text-align: center" :rules="signInfoRules">
        <el-form-item label="账号" prop="user">
          <el-input v-model="signInfo.user"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="signInfo.password" type="password"></el-input>
        </el-form-item>

        <div v-if="signInFormLoading">
          <i class="el-icon-loading"></i>
        </div>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="signInFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="clickSignIn('signInfo')">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import ElButton from "../../../node_modules/element-ui/packages/button/src/button.vue";

  export default {
    components: {ElButton},
    name: 'Alink',
    data () {
      return {
        stateIndex: 0,
        stateType: ["info", "warning", "primary"],
        state: ['未连接服务器', '未登入', '登入成功'],
        loginType: ["primary", "success", "info"],
        loginState: ['连接', '登入', '登出'],

        phoneIndex: 0,
        phoneType: ["info", "warning", "success"],
        phoneState: ['未通话', '外呼中', '通话中'],
        phoneIsJingYin: false,

        signInFormVisible: false,
        signInFormLoading: false,
        signInfoRules: {
          user: [
            { required: true, message: '请输入账号', trigger: 'blur' }
          ],
          password: [
            { required: true, message: '请输入密码', trigger: 'blur' }
          ]
        },
        signInfo: {
          user: '',
          password: ''
        },

        inputPhone: '', // 输入的手机号
        canHuangUpVisible: false, // 是否能挂断电话

        local_linker: null,
        link_ip: '10.100.5.121',
        link_port: 6111,

        callTime:  0,    // 通话时长，单位 s
        callMinute: '0',
        callSecond: '00',
        timer: false
      }
    },
    created() {
    },
    methods: {
      test(phone) {
        console.info(phone);
      },
      // 连接服务按钮
      clickDengLu() {
        switch (this.stateIndex) {
          case 0: { // 账号密码框
            this.signInFormVisible = true;
            break;
          }
          case 1: { // 签入
            this.local_linker.Login();
            break;
          }
          case 2: { // 签出
            this.local_linker.Logout();
            break;
          }
        }
      },

      // 开始电话计时
      startCallTime() {
        this.stopCallTime();
        this.timer = true;
        this.startCallTime2();
      },
      startCallTime2() {
        setTimeout(() => {
          if (this.timer) {
            this.startCallTime2();
          }
          this.callTime++;
          this.callMinute = parseInt(this.callTime / 60);
          let second = this.callTime % 60;
          this.callSecond = second < 10 ? '0' + second : second;
        }, 1000);
      },
      stopCallTime() {
        this.timer = false;
        this.callTime = 0;
      },

      // 点击连接服务器，输入账号密码后连接外呼服务器
      clickSignIn(formName) {
        this.$refs[formName].validate((valid) => {
          if (!valid) {
            return false;
          }
          this.signInFormLoading = true;
          this.signIn();
        });
      },

      clickLogin() {
        if (this.local_linker === null || this.stateIndex === 0) {
          this.$notify.error("还未连接服务器，请先连接服务器");
          return;
        }

        if (this.stateIndex === 1) {
          // 签入
          this.local_linker.Login();
        } else if (this.stateIndex === 2) {
          // 签出
          this.local_linker.Logout();
        }
      },

      clickWaiHu() {
        if (this.stateIndex !== 2) {
          this.$notify.error("未登入");
          return;
        }

        console.info(this.inputPhone);

        switch (this.phoneIndex) {
          case 0: { //进行呼叫
            if (this.inputPhone === null  || this.inputPhone === '' || this.inputPhone.length !== 11) {
              this.$notify.error("输入手机号不合法");
              return;
            }
            this.phoneIndex = 1;
            this.local_linker.MakeCall(this.inputPhone);
            break;
          }
          case 1:
          case 2: { // 挂电话
            this.phoneIndex = 0;
            this.local_linker.Hangup();
            break;
          }
          default: {
            break;
          }
        }


      },
//      // 挂电话
//      clickHuangUp() {
//        if (this.local_linker === null || this.stateIndex === 0) {
//          this.$notify.error("还未连接服务器，请先连接服务器");
//          return;
//        }
//        if (this.stateIndex !== 2) {
//          this.$notify.error("还未签入，请先签入在进行外呼操作");
//          return;
//        }
//
//        this.local_linker.Hangup();
//      },
      // 电话静音
      clickJingYin() {
        if (this.stateIndex !== 2) {
          this.$notify.error("未登入");
          return;
        }

        if (this.phoneIsJingYin) {
          this.local_linker.CaptureSound(true);
          console.info('取消静音')
        } else {
          this.local_linker.CaptureSound(false);
          console.info('静音')
        }
        this.phoneIsJingYin = !this.phoneIsJingYin;
      },
      clickZhuanJie() {
        if (this.stateIndex !== 2) {
          this.$notify.error("未登入");
          return;
        }

        this.$prompt('请输入要转接的号码', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          inputPattern: /^[0-9]{6,11}$/,
          inputErrorMessage: '号码格式不正确'
        }).then(({ value }) => {
          this.local_linker.TransferCall(value);
          this.$notify.success("已转接到 " + value);
        }).catch(() => {});

      },

      // 连接服务器
      signIn() {
        if (this.local_linker !== null) {
          this.local_linker.Shutdown();
          this.local_linker = null;
        }

        // 登录信息
        let signInfo = {
          address: this.link_ip,
          port: this.link_port,
          extension: this.signInfo.user,  // 分机号
          passwd: this.signInfo.password, // 密码
          useSipPhone: true,
          autoanswer: true,
        };

        let th = this;
        let notify = this.$notify;
        this.local_linker = new LXKJ.Linker();
        console.log('-------- init local_linker --------');

        this.local_linker.on('loaded', (event) => {
          setTimeout(() => {
            console.info('加载成功');
            if (th.local_linker !== null) {
              console.info('开始连接');
              th.local_linker.Login();
            }
          }, 3000) // 建议根据网络情况调整该值
        });

        // 连接成功回调
        this.local_linker.on("connected", function (event) {
          th.$message.success('连接成功');
          console.info('连接成功 ' + JSON.stringify(event.data));
          th.stateIndex = 1;
          th.signInFormVisible = false;
          th.signInFormLoading = false;
        });

        // 签入成功
        this.local_linker.on("logined", function (event) {
          th.$message.success('登入成功');
          console.info('签入成功 '  + JSON.stringify(event.data));
          th.stateIndex = 2;
        });

        // 签出或断开
        this.local_linker.on('logout', function (event) {
          th.$message.success('签出或断开成功');
          console.info('签出或断开 ' + JSON.stringify(event.data));
          th.stateIndex = 1;
          th.phoneIndex = 0;
          $("#btnJingYin").text('静音');
        });

        // 状态变化消息回调
        this.local_linker.on("statechanged", function (event) {
          let evData = event.data;
          console.log("状态变化消息回调, 当前状态:" + STATUS_CHN_NAME[evData.newstate]);

          switch(evData.newstate) {
            case 0: {  // 不可用
              th.stopCallTime();
              break;
            }
            case 1: { // 空闲
              th.stopCallTime();
              break;
            }
            case 2: { // 摘机
              break;
            }
            case 3:break;//拨号     拨号就立马摘机
            case 4:break;//按键
            case 5:break;//振铃
            case 6: { // 通话   启动计时器，改变状态
              th.phoneIndex = 2;
              th.startCallTime();
              break;
            }
            case 9:break;//催挂
          }
        });

        // 来电消息回调
        this.local_linker.on("incoming", function (event) {
          console.log("来电消息回调 incoming:", JSON.stringify(event.data));
          th.canHuangUpVisible = true;
          th.phoneIndex = 1;
        });

        // 操作结果返回
        this.local_linker.on('operate', function (event) {
          let d = event.data;
          console.info("执行操作: " + "operate: operate:" + d.operate + "  value:" + d.value + "  result:" + d.result)
        });

        //通话已结束  提醒
        this.local_linker.on("hangup",function (event) {
          notify.success({message: '通话已结束, 通话时长 ' + th.callMinute + ':' + th.callSecond});
          console.info('通话已结束 ' + JSON.stringify(event.data));
          th.canHuangUpVisible = false;
          th.phoneIndex = 0;
          $("#btnJingYin").text('静音');
        });


        // 录音地址消息回调
        this.local_linker.on("recording", function (event) {
          th.phoneIndex = 2;
          console.info("接收到录音地址: <a href=\"" + event.data.recordUrl + "\" target=\"_Blank\">" + event.data.recordUrl + "</a>");
        });

        // 签入 失败
        this.local_linker.on("loginedFailed", function (event) {
          th.phoneIndex = 0;
          console.warn('登录失败');
          console.info('登录失败 ' + JSON.stringify(event.data));
          $("#btnJingYin").text('静音');
        });

        // 录音地址消息回调
        this.local_linker.on("notification", function (event) {
          th.phoneIndex = 2;
          var d = event.data;
          console.info("录音地址消息回调，Head:" + d.head + "  Data:" + d.data);
        });

        // 失败事件
        this.local_linker.on("failed", function (event) {
          let d = event.data;
          console.warn("CTI失败，类型：" + d.type + ' 消息: ' + d.cause);

          if (d.type === 'loadconfig' && d.cause === 'Invalid extension.') {
            notify.error({ message: "用户名或密码错误" });
          } if (d.type === 'FSLogin' && d.cause === 'Phone login failed.') {
            notify.error({ message: "用户名或密码错误" });
          } else {
            notify.error({
              title: "CTI失败，类型：" + d.type,
              message: ' 消息:' + d.cause
            });
          }
        });

        this.local_linker.LoadConfig(signInfo);
      }
    }
  }
</script>

<style scoped lang="less">
  @import url("//at.alicdn.com/t/font_695662_x5d5j4csadm6xbt9.css");

  i {
    font-size: 18px;
  }
</style>
